package repository

// 抽出一些重复使用的代码
import (
	"learningProject/vueGoProject/common"
	"learningProject/vueGoProject/model"
)

type CategoryRepository struct {
}

func NewCategoryRepository() CategoryRepository {
	return CategoryRepository{}
}

func (c CategoryRepository) Create(name string) (*model.Category, error) {
	category := model.Category{
		Name: name,
	}

	if err := common.DB.Create(&category).Error; err != nil {
		return nil, err
	}
	return &category, nil
}

func (c CategoryRepository) Update(category model.Category, name string) (*model.Category, error) {
	if err := common.DB.Model(&category).Update("name", name).Error; err != nil {
		return nil, err
	}
	return &category, nil
}

func (c CategoryRepository) SelectById(id int) (*model.Category, error) {
	category := model.Category{}
	if err := common.DB.First(&category, id).Error; err != nil {
		return nil, err
	}
	return &category, nil
}

func (c CategoryRepository) DeleteById(id int) error {
	category := model.Category{}
	if err := common.DB.Delete(&category, id).Error; err != nil {
		return err
	}
	return nil
}
